const Koa = require('koa')
const app = new Koa()
const json = require('koa-json')
const onerror = require('koa-onerror')
const bodyparser = require('koa-bodyparser')()
const logger = require('koa-logger')
const spider = require('./controller/spider.js')
const Router = require('koa-router')
const router = new Router()
const Nightmare = require('nightmare')
const nightmare = Nightmare({ show: true })
const send = require('koa-send')
const config = require('./config')
const fs = require('fs')

// error handler
onerror(app)
// middlewares
app.use(bodyparser)
app.use(json())
app.use(logger())
// logger
app.use(async (ctx, next) => {
  const start = new Date()
  await next()
  const ms = new Date() - start
  console.log(`${ctx.method} ${ctx.url} - ${ms}ms`)
})

app.use(async (ctx, next) => {
  try {
    ctx.error = ({ data, msg, status, error }) => {
      ctx.status = status || 400
      ctx.body = { code: -200, msg, data, error }
    }
    ctx.success = ({ data, msg }) => {
      ctx.body = { code: 200, msg, data }
    }
    await next()
  } catch (err) {
    if (!err) {
      return ctx.error({ msg: new Error('未知错误!') })
    }
    if (typeof err == 'string') {
      return ctx.error({ msg: new Error(err) })
    }
    ctx.error({ msg: '服务器错误!', error: err, status: ctx.status })
  }
})

router.get('/api/', async ctx => {
  await spider.api(ctx)
})

router.get('/api/:title', async ctx => {
  await spider.api(ctx)
})

router.get('/own/', async ctx => {
  await spider.own(ctx)
})

router.get('/own/:title', async ctx => {
  await spider.own(ctx)
})

router.get('/data', async ctx => {
  await spider.data(ctx)
})

router.get('/data/:title', async ctx => {
  await spider.data(ctx)
})

router.get('/export/:type', async ctx => {
  let { type } = ctx.params
  let path = `${config.exportDir}/${type}.js`
  if (fs.existsSync(path)) {
    ctx.attachment(path)
    await send(ctx, path)
    return ctx.success({ msg: '下载成功!' })
  }
  return ctx.error({ msg: '文件不存在!', data: path })
})

router.get('/test/:title', async ctx => {
  let body = await nightmare
    .goto('http://roll.news.qq.com/')
    .wait(() => document.querySelectorAll('#artContainer li').length > 0)
    .evaluate(() => document.body.innerHTML)
    .end()
    .catch(function(error) {
      console.error('Search failed:', error)
    })

  ctx.success({ data: JSON.stringify(body) })
})

router.get('/test1/:title', async ctx => {
  let body = await nightmare
    .goto('http://roll.news.qq.com/')
    .wait(() => {
      if (document.querySelectorAll('#artContainer li').length > 0) {
        window.list = []
        return true
      }
    })
    .wait(() => {
      document.querySelectorAll('#artContainer li').forEach(element => {
        const obj = {
          title: element.querySelector('a').innerHTML,
          time: element.querySelector('.t-time').innerHTML
        }
        list.push(obj)
      })

      const next_page_button = document.querySelector(
        '#pageArea .f12:last-child'
      )
      if (next_page_button) {
        next_page_button.click()
        return false
      }

      return true
    })
    .evaluate(() => list)
    .end()
    .catch(function(error) {
      console.error('Search failed:', error)
    })

  ctx.success({ data: JSON.stringify(body) })
})

app.use(router.routes()).use(router.allowedMethods())
module.exports = app

// 端口占用查看及杀掉
// netstat -ano | findstr :3000/
// taskkill -PID 18412 -F
// lsof -i:3000
// kill -9 26993

// wait 策略：loading不见（!document.querySelector(".loading")）或 列表出现（document.querySelectorAll("#artContainer li").length>0）
// wait(2500)是下下策
